package com.argrace.smart.util;

import android.app.ActivityManager;
import android.content.Context;
import android.os.SystemClock;
import android.util.Log;

import com.aliyun.alink.business.alink.ALinkBusinessEx;
import com.aliyun.alink.sdk.net.anet.api.AError;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryRequest;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryResponse;
import com.argrace.smart.model.LocalDb_QingJing_DeviceTable;
import com.argrace.smart.model.LocalDb_QingJingTable;

import org.litepal.crud.DataSupport;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import static android.content.Context.ACTIVITY_SERVICE;

/**
 * Created by Administrator on 2018\2\18 0018.
 */

public class utils {
    public static String getTheJson(Map<String, String> params) {

        StringBuffer sb = new StringBuffer();
        sb.append("{");
        Iterator<Map.Entry<String, String>> it = params.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> entry = it.next();
            sb.append("\"").append(entry.getKey()).append("\":\"").append(entry.getValue()).append("\"").append(",");
        }
        sb.deleteCharAt(sb.length() - 1).append("}");
        return sb.toString();

    }

    public static void executeQingJing(LocalDb_QingJingTable bean) {
        if (bean == null) {
            return;
        }
        //新增加根据时段处理
        if (bean.getName().equals("客厅回家模式") || bean.getName().equals("全局回家模式") || bean.getName().equals("全局中控回家")) {
            long time = System.currentTimeMillis();
            Calendar mCalendar = Calendar.getInstance();
            mCalendar.setTimeInMillis(time);
            int mHour = mCalendar.get(Calendar.HOUR);
            if (mHour % 2 == 0) {
                List<LocalDb_QingJing_DeviceTable> beans = DataSupport.where("LocalDb_DeviceTable_deviceId = ?", "客厅回家模式白天").find(LocalDb_QingJing_DeviceTable.class);
                if (beans != null) {
                    for (int i = 0; i < beans.size(); i++) {
                        executeDevice(beans.get(i));
                    }

                }
            } else {
                List<LocalDb_QingJing_DeviceTable> beans = DataSupport.where("LocalDb_DeviceTable_deviceId = ?", bean.getName()).find(LocalDb_QingJing_DeviceTable.class);
                if (beans != null) {
                    for (int i = 0; i < beans.size(); i++) {
                        executeDevice(beans.get(i));
                    }

                }
            }
            return;
        }
        if (bean.getName().equals("客厅日常模式")) {
            long time = System.currentTimeMillis();
            Calendar mCalendar = Calendar.getInstance();
            mCalendar.setTimeInMillis(time);
            int mHour = mCalendar.get(Calendar.HOUR_OF_DAY);
            if (mHour >= 6 && mHour <= 18) {
                List<LocalDb_QingJing_DeviceTable> beans = DataSupport.where("LocalDb_DeviceTable_deviceId = ?", bean.getName()).find(LocalDb_QingJing_DeviceTable.class);
                if (beans != null) {
                    for (int i = 0; i < beans.size(); i++) {
                        executeDevice(beans.get(i));
                    }

                }
            } else {
                List<LocalDb_QingJing_DeviceTable> beans = DataSupport.where("LocalDb_DeviceTable_deviceId = ?", "客厅日常模式夜晚").find(LocalDb_QingJing_DeviceTable.class);
                if (beans != null) {
                    for (int i = 0; i < beans.size(); i++) {
                        executeDevice(beans.get(i));
                    }
                }
            }
            return;
        }
        final List<LocalDb_QingJing_DeviceTable> beans = DataSupport.where("LocalDb_DeviceTable_deviceId = ?", bean.getName()).find(LocalDb_QingJing_DeviceTable.class);
        if (beans != null) {
            if (beans.size() > 15) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        executeDevice_DelayedBy500(beans);
                    }
                }).start();

                return;
            }
            for (int i = 0; i < beans.size(); i++) {
                executeDevice(beans.get(i));
            }
        }
    }

    public static void executeDevice_DelayedBy500(List<LocalDb_QingJing_DeviceTable> beans) {
        for (LocalDb_QingJing_DeviceTable bean : beans) {
            if (bean == null) {
                return;
            }
            if (bean.getJson_params() == null || bean.getJson_params().equals("")) {
                return;
            }
            Log.i("info", "executeDevice()start,params=" + bean.getJson_params() + "---uuid" + bean.getUuid());
            SystemClock.sleep(500);
            String method = "mtop.openalink.app.core.device.set.status";
            HashMap<String, Object> params = new HashMap<>();
            params.put("uuid", bean.getUuid());
            params.put("setParams", bean.getJson_params());
            AlinkHttpUtil.AlinkHttpRequest(method, params, new ALinkBusinessEx.IListener() {
                @Override
                public void onSuccess(TransitoryRequest transitoryRequest, TransitoryResponse transitoryResponse) {
                    Log.i("info", "executeDevice执行成功，params=" + transitoryResponse.data);
                }

                @Override
                public void onFailed(TransitoryRequest transitoryRequest, AError aError) {
                    Log.i("info", "executeDevice执行失败,code=" + aError.getSubCode());
                }
            });
        }
    }

    public static void executeDevice(LocalDb_QingJing_DeviceTable bean) {
        if (bean == null) {
            return;
        }
        if (bean.getJson_params() == null || bean.getJson_params().equals("")) {
            return;
        }
        Log.i("info", "executeDevice()start,params=" + bean.getJson_params() + "---uuid" + bean.getUuid());
        String method = "mtop.openalink.app.core.device.set.status";
        HashMap<String, Object> params = new HashMap<>();
        params.put("uuid", bean.getUuid());
        params.put("setParams", bean.getJson_params());
        AlinkHttpUtil.AlinkHttpRequest(method, params, new ALinkBusinessEx.IListener() {
            @Override
            public void onSuccess(TransitoryRequest transitoryRequest, TransitoryResponse transitoryResponse) {
                Log.i("info", "executeDevice执行成功，params=" + transitoryResponse.data);
            }

            @Override
            public void onFailed(TransitoryRequest transitoryRequest, AError aError) {
                Log.i("info", "executeDevice执行失败,code=" + aError.getSubCode());
            }
        });
    }

    //查询当前service是否再运行
    public static boolean isServiceRunning(Context context, Class clazz) {
        ActivityManager manager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (clazz.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }
}
